package com.naizhuai.ui.task;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.naizhuai.R;
import com.naizhuai.network.apistore.TaskActionApiStore;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.CustomTextWatch;
import com.naizhuai.ui.components.MultStateView;
import com.naizhuai.ui.entity.UserLeader;
import com.naizhuai.util.DrawableUtils;
import com.naizhuai.util.NaizhuAILog;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observer;

public class SearchUserActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.search_view)
    EditText searchView;
    @BindView(R.id.stateView)
    MultStateView stateView;
    @BindView(R.id.listview)
    ListView listview;
    private TaskActionApiStore mTaskActionApiStore;
    private List<UserLeader> mCacheUserLeaders;
    private UserSearchAdapter mSearchAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        toolbar.setNavigationOnClickListener(v -> finish());
        searchView.addTextChangedListener(mTextWatcher);
        searchView.requestFocus();
        initData();
        stateView.setOnRetryClickListener(v -> loadUserLeader());
    }

    private void initData() {
        if (mTaskActionApiStore == null) {
            mTaskActionApiStore = TaskActionApiIml.getInstance();
        }
        loadUserLeader();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void loadUserLeader() {
        stateView.showView(MultStateView.STATUS_LOADING);
        mTaskActionApiStore.User_Leader("2")
                .subscribe(new Observer<List<UserLeader>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        NaizhuAILog.e(e.getMessage());
                    }

                    @Override
                    public void onNext(List<UserLeader> userLeaderList) {
                        NaizhuAILog.e(userLeaderList.size() + "");
                        addData(userLeaderList);
                        mCacheUserLeaders=userLeaderList;
                        if (userLeaderList.size()>0){
                            mSearchAdapter=new UserSearchAdapter(mCacheUserLeaders);
                            listview.setAdapter(mSearchAdapter);
                            stateView.showView(MultStateView.STATUS_CONTENT);
                        }else {
                            stateView.showView(MultStateView.STATUS_EMPTY);
                        }

                    }
                });
    }

    private void addData(List<UserLeader> list) {
        list.add(new UserLeader("1","","李晨希"));
        list.add(new UserLeader("1","","韩博文"));
        list.add(new UserLeader("1","","李晨希"));
        list.add(new UserLeader("1","","韩博文"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
        list.add(new UserLeader("1","","张珂"));
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_search_user;
    }

    private final TextWatcher mTextWatcher = new CustomTextWatch() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            mSearchAdapter.setQuery(s != null ? s.toString() : null);
        }
    };

    public final class UserSearchAdapter extends BaseAdapter implements Filterable {
        private List<UserLeader> userLeaderList;
        private Filter mFilter;
        private String mQuery;
        private UserSearchAdapter(List<UserLeader> userLeaderList) {
            this.userLeaderList = userLeaderList;
            mFilter=new WordFilter(userLeaderList);
        }

        @Override
        public int getCount() {
            return userLeaderList != null ? userLeaderList.size() : 0;
        }

        @Override
        public Object getItem(int position) {
            return userLeaderList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Filter getFilter() {
            return mFilter;
        }
        public void setQuery(String query) {
            if (!Objects.equals(query, mQuery)) {
                getFilter().filter(query);
            }
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            UserLeader leader=userLeaderList.get(position);
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.adapter_userleader_item, parent, false);
                holder=new ViewHolder(convertView);
                convertView.setTag(holder);
            }else {
                holder=(ViewHolder)convertView.getTag();
            }

            if (TextUtils.isEmpty(leader.thumb)){
                holder.userAvatar.setImageDrawable(DrawableUtils.setTextDrawable(leader.username));
            }else {
                Glide.with(parent.getContext()).load(leader.thumb).into(holder.userAvatar);
            }

            holder.UserName.setText(leader.username);
            holder.container.setOnClickListener(v -> {
                Intent intent=new Intent();
                intent.putExtra("leader",leader);
                setResult(RESULT_OK,intent);
                finish();
            });
            return convertView;
        }
        private final class WordFilter extends Filter {

            private final List<UserLeader> mItems;

            private WordFilter(List<UserLeader> items) {
                mItems = new ArrayList<>(items);
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final List<UserLeader> list;

                if (TextUtils.isEmpty(constraint)) {
                    list = mItems;
                } else {
                    list = new ArrayList<>();
                    for(UserLeader leader:mItems){
                        String name=leader.username;
                        if (name.contains(constraint.toString())){
                            list.add(leader);
                        }
                    }
                }

                final FilterResults results = new FilterResults();
                results.values = list;
                results.count = list.size();
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                userLeaderList = (List<UserLeader>) results.values;
                mQuery = constraint != null ? constraint.toString() : null;
                mSearchAdapter.notifyDataSetChanged();
            }
        }
        class ViewHolder {
            @BindView(R.id.user_head_logo)
            ImageView userAvatar;
            @BindView(R.id.user_name)
            TextView UserName;
            @BindView(R.id.container)
            ViewGroup container;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

}

